package com.heritcoin.coin.lib.util.bitmap

import android.graphics.*
import java.io.FileInputStream

class BitmapRegionDecoder private constructor(private val decoder: android.graphics.BitmapRegionDecoder) {

    companion object {
        fun newInstance(imagePath: String): BitmapRegionDecoder? {
            val decoder = android.graphics.BitmapRegionDecoder.newInstance(FileInputStream(imagePath), false)
            return if (decoder == null) {
                null
            } else {
                BitmapRegionDecoder(decoder)
            }
        }
    }

    fun decodeRegion(rect: Rect, option: BitmapFactory.Options, rotation: Float): Bitmap? {
        return if (rotation == 0f) {
            decoder.decodeRegion(rect, option)
        }else{
            val width = decoder.width
            val height = decoder.height
            val matrix = Matrix()
            matrix.setRotate(-rotation) //先旋转
            val adjusted = RectF()
            matrix.mapRect(adjusted, RectF(rect))
            val dx = if (adjusted.left < 0) width else 0
            val dy = if (adjusted.top < 0) height else 0
            adjusted.offset(dx.toFloat(), dy.toFloat())
            val newRect = Rect(
                adjusted.left.toInt(),
                adjusted.top.toInt(),
                adjusted.right.toInt(),
                adjusted.bottom.toInt()
            )
            val bitmap = decoder.decodeRegion(newRect, option)//截取
            if (bitmap == null) {
                null
            } else {
                val rotateMatrix = Matrix()
                rotateMatrix.postRotate(rotation)//截取完，再旋转用于显示正确
                Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, rotateMatrix, true)
            }
        }
    }

    fun recycle() {
        decoder.recycle()
    }

}